package com.luoyx.vjsb.admin.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luoyx.vjsb.authority.security.manager.MySecurityMetadataSource;
import com.luoyx.vjsb.common.annotation.Logs;
import com.luoyx.vjsb.common.query.CommonQuery;
import com.luoyx.vjsb.common.util.AjaxResult;
import com.luoyx.vjsb.core.entity.SysRole;
import com.luoyx.vjsb.core.entity.SysRolePermission;
import com.luoyx.vjsb.core.service.ISysRolePermissionService;
import com.luoyx.vjsb.core.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiang.github.io</p>
 * @since 2020/3/26 15:05
 */
@RestController
@RequestMapping("role")
@Api(tags = "系统角色")
public class SysRoleController {

    @Resource
    private ISysRoleService iSysRoleService;

    @Resource
    private ISysRolePermissionService iSysRolePermissionService;

    @Resource
    private MySecurityMetadataSource mySecurityMetadataSource;

    @PostMapping("list")
    @ApiOperation(value = "获取角色分页信息")
    public AjaxResult<Page<SysRole>> list(CommonQuery commonQuery) {
        Page<SysRole> page = iSysRoleService.page(new Page<>(commonQuery.getCurrent(), commonQuery.getSize()));
        return AjaxResult.success(page);
    }

    @GetMapping("getRoles")
    @ApiOperation(value = "获取全部角色")
    public AjaxResult<List<SysRole>> getRoles() {
        return AjaxResult.success(iSysRoleService.list());
    }

    @PostMapping("addRole")
    @ApiOperation(value = "添加角色")
    @Logs(value = "添加角色")
    public AjaxResult<String> add(@RequestBody SysRole role) {
        SysRole one = iSysRoleService.getOne(new QueryWrapper<SysRole>().eq("role_name", role.getRoleName()));
        if (one != null) {
            return AjaxResult.error("角色已存在！");
        }
        role.setCreateTime(DateUtil.date())
            .setUpdateTime(DateUtil.date());
        boolean save = iSysRoleService.save(role);
        if (save) {
            addRolePermission(role);
            mySecurityMetadataSource.loadResourceDefine();
        }
        return save ? AjaxResult.success("添加角色成功") : AjaxResult.error("添加角色失败");
    }

    @PatchMapping("updateRole")
    @ApiOperation(value = "修改角色")
    @Logs(value = "修改角色")
    public AjaxResult<String> update(@RequestBody SysRole role) {
        role.setUpdateTime(DateUtil.date());
        boolean b = iSysRoleService.updateById(role);
        if (b) {
            iSysRolePermissionService.remove(new QueryWrapper<SysRolePermission>().eq("role_id", role.getId()));
            addRolePermission(role);
            mySecurityMetadataSource.loadResourceDefine();
        }
        return b ? AjaxResult.success("修改角色成功") : AjaxResult.error("修改角色失败");
    }

    @DeleteMapping("deleteRole")
    @ApiOperation(value = "删除角色")
    @Logs(value = "删除角色")
    public AjaxResult<String> del(String[] ids) {
        boolean b = iSysRoleService.removeByIds(Arrays.asList(ids));
        if (b) {
            for (String id : ids) {
                iSysRolePermissionService.remove(new QueryWrapper<SysRolePermission>().eq("role_id", id));
                mySecurityMetadataSource.loadResourceDefine();
            }
        }
        return b ? AjaxResult.success("删除角色成功") : AjaxResult.error("删除角色失败");
    }

    private void addRolePermission(SysRole role) {
        List<SysRolePermission> permissions = new ArrayList<>(role.getPermissionIds().size());
        role.getPermissionIds().forEach(id -> {
            SysRolePermission permission = new SysRolePermission();
            permission.setPermissionId(id)
                .setRoleId(role.getId())
                .setCreateTime(DateUtil.date())
                .setUpdateTime(DateUtil.date());
            permissions.add(permission);
        });
        iSysRolePermissionService.saveBatch(permissions);
    }
}
